<template>
  <div class="fill-width-height">

    <el-tabs v-model="activeName" @tab-click="handleClick" class="fill-height flex-col">
      <el-tab-pane label="全部" name="all" class="fill-height">
        <div class="flex-col fill-height" >
          <el-row :gutter="12" style="margin: 0;overflow: auto;flex:1;">
            <el-col :span="24" :xs="12" :sm="12" :md="4" :lg="4" v-for="item in thumbnailList" :key="item.imageId" style="padding: 6px;" >
              <el-card class="thumbnail-card" style="cursor: pointer;" @click="handleCardClick(item)">
                <template #header>
                  <div class="fill-width flex-row justify-center align-center">
                    <el-checkbox
                      v-model="item.selected"
                      @change="handleThumbnailSelect(item)"
                    ></el-checkbox>
                    <div class="flex-1"></div>
                    <div class="flex-row" style="gap: 10px">
                      <el-button type="text" text @click="copyPath(item.imageSrc)" >复制路径</el-button>
                    </div>
                  </div>
                </template>
                <div class="fill-width-height flex-col flex-1" style="min-height: 0;"  @click="handleCardClick(item)">
                  <div class="flex-1 image-wrapper">
                    <LazyLoadImage :src="item.imageSrc" fit="contain" class="fill-height"></LazyLoadImage>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <!-- 缩略图列表操作栏 -->
          <div v-if="thumbnailList.length > 0" class="thumbnail-actions">
            <el-row :gutter="12" style="margin:0;width: 100%;">
              <!-- 历史记录列表 -->
              <el-col :span="24" :xs="24" :sm="4" :md="4" :lg="4">
                <div class="flex-row flex-wrap">
                  <el-checkbox v-model="isAllSelected" @change="handleSelectAll">全选/反选</el-checkbox>
                </div>
              </el-col>
              <el-col :span="24" :xs="24" :sm="20" :md="20" :lg="20">
                <pagination
                  :total="notExistsRecordsTotal"
                  :page-sizes="[100, 200, 500,1000,2000]"
                  :page.sync="notExistsRecordsQueryParams.pageNum"
                  :limit.sync="notExistsRecordsQueryParams.pageSize"
                  @pagination="getNotExistsRecords(activeBillId)"
                  style="margin: 0!important; height: 100%; padding: 0!important; position: unset;"
                />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="批次" name="bill" class="fill-height" v-if="isShowBillTab">
        <el-row :gutter="12" class="fill-height">
          <!-- 历史记录列表 -->
          <el-col :span="24" :xs="12" :sm="8" :md="8" :lg="6" style="height: 100%;">
            <div class="flex-col history-list-container">
              <!-- 新增的标题框 -->
              <div class="history-list-title">
                <h2>历史记录列表</h2>
              </div>
              <div class="flex-1 history-records-wrapper">
                <div class="overflow-auto history-records">
                  <div
                    v-for="record in historyRecords"
                    :key="record.id"
                    @click="getThumbnailList(record.id)"
                    class="history-record-item"
                    :class="{'selected': record.selected}"
                  >
                    <p><strong>批次ID：</strong> {{ record.id }}</p>
                    <p><strong>爬取URL：</strong>{{ record.urls }}</p>
                    <p><strong>备注：</strong>{{ record.title }}</p>
                  </div>
                </div>
              </div>
              <div class="pagination-container">
                <el-divider style="margin: 0!important;"/>
                <pagination
                  small
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  :page-sizes="[100, 200, 500,1000]"
                  @pagination="getHistoryRecords"
                />
              </div>
            </div>
          </el-col>
          <!-- 缩略图列表 -->
          <el-col :span="24" :xs="12" :sm="16" :md="16" :lg="18" style="height: 100%;">
            <div class="flex-1 thumbnail-container">
              <div class="flex-1 thumbnail-card-wrapper">
                <div v-if="thumbnailList.length > 0" class="overflow-auto thumbnail-card-container align-center justify-start">
                  <el-row :gutter="12" style="margin: 0;height: 100%;">
                    <el-col :span="24" :xs="12" :sm="12" :md="4" :lg="4" v-for="item in thumbnailList" :key="item.imageId" style="padding: 6px;" >
                      <el-card class="thumbnail-card" style="cursor: pointer;" @click.native="handleCardClick(item)">
                        <template #header>
                          <el-checkbox
                            v-model="item.selected"
                            @change="handleThumbnailSelect(item)"
                          ></el-checkbox>
                        </template>
                        <div class="fill-width-height flex-col flex-1" style="min-height: 0;" >
                          <div class="flex-1 image-wrapper">
                            <LazyLoadImage :src="item.imageSrc" fit="contain" class="fill-height"></LazyLoadImage>
                          </div>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
                <div v-if="!thumbnailList.length" class="no-thumbnail-message">暂无缩略图记录</div>
              </div>
              <!-- 缩略图列表操作栏 -->
              <div v-if="thumbnailList.length > 0" class="thumbnail-actions">
                <el-row :gutter="12" style="margin:0px;width: 100%;">
                  <!-- 历史记录列表 -->
                  <el-col :span="24" :xs="24" :sm="4" :md="4" :lg="4">
                    <div class="flex-row flex-wrap">
                      <el-checkbox v-model="isAllSelected" @change="handleSelectAll">全选/反选</el-checkbox>
                    </div>
                  </el-col>
                  <el-col :span="24" :xs="24" :sm="20" :md="20" :lg="20">
                    <pagination
                      :total="thumbnailTotal"
                      :page-sizes="[100, 200, 500,1000]"
                      :page.sync="thumbnailQueryParams.pageNum"
                      :limit.sync="thumbnailQueryParams.pageSize"
                      @pagination="getThumbnailList(activeBillId)"
                      style="margin: 0!important; height: 100%; padding: 0!important; position: unset;"
                    />
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  billPage,
  billDetailPage,
} from '@/api/imgManage/imageCrawler'
import LazyLoadImage from '@/components/LazyLoadImage'
import { getNotExistsRecords } from '@/api/imgManage/image'
import { debounce } from '@/utils'

export default {
  components: {
    LazyLoadImage
  },
  props: {
    isSingle: {
      type: Boolean,
      default: () => false
    },
    isShowBillTab: {
      type: Boolean,
      default: () => true
    }
  },
  data() {
    return {
      activeName: 'all',
      selectList: [],
      historyRecords: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      thumbnailQueryParams: {
        pageNum: 1,
        pageSize: 1000
      },
      thumbnailTotal: 0,
      thumbnailList: [],
      isAllSelected: false,
      activeBillId: null, // 记录当前激活的批次 ID
      selectedIds: new Set(), // 使用 Set 存储选中的缩略图 ID
      allThumbnailData: {}, // 存储所有批次的缩略图数据

      notExistsRecordsQueryParams: {
        pageNum: 1,
        pageSize: 1000
      },
      notExistsRecordsList: [],
      notExistsRecordsTotal: 0
    }
  },
  methods: {
    async copyPath(imageSrc) {
      try {
        await navigator.clipboard.writeText(imageSrc);
        this.$message.success('复制成功')
      } catch (error) {
        console.error('复制失败:', error);
      }
    },
    async getNotExistsRecords(){
      this.$modal.loading("查询中，请稍候...");
      const res = await getNotExistsRecords(this.notExistsRecordsQueryParams).catch(e => {
        this.$modal.closeLoading()
      })
      const rows = res?.rows?.map(item => ({
        imageId: item.id,
        imageSrc: item.imageUrl,
        selected: this.selectedIds.has(item.id)
      }))
      this.thumbnailList = rows
      this.$modal.closeLoading()
      this.notExistsRecordsTotal = res.total
      if(!this.allThumbnailData['all']){
        this.allThumbnailData['all'] = []
      }
      this.allThumbnailData['all'] = this.allThumbnailData['all'].concat(rows)
    },
    // 获取历史记录
    async getHistoryRecords() {
      try {
        const paramms = {
          ...this.queryParams,
          status: 'COMPLETED'
        }
        const response = await billPage(paramms)
        this.historyRecords = response.rows
        this.total = response.total || 0
      } catch (error) {
        console.error('获取历史记录失败', error)
      }
    },
    selectHistoryRow(currentBillId){
      this.historyRecords.forEach(item => {
        item.selected = false
        if(item.id === currentBillId){
          item.selected = true
        }
      })
    },
    // 获取缩略图列表
    async getThumbnailList(currentBillId) {
      this.selectHistoryRow(currentBillId)
      this.activeBillId = currentBillId
      try {
        const params = {
          crawlerBillId: currentBillId,
          ...this.thumbnailQueryParams
        }
        const response = await billDetailPage(params)
        const rows = response.rows.map(item => ({
          imageId: item.id,
          imageSrc: item.imageUrl,
          selected: this.selectedIds.has(item.id)
        }))
        if (!this.allThumbnailData[currentBillId]) {
          this.allThumbnailData[currentBillId] = []
        }
        this.allThumbnailData[currentBillId] = this.allThumbnailData[currentBillId].concat(rows)
        this.thumbnailList = rows
        this.thumbnailTotal = response.total || 0 // 更新缩略图总记录数
        this.updateSelectAllStatus() // 更新全选状态
      } catch (error) {
        console.error('获取缩略图列表失败', error)
        this.$message.error('获取缩略图列表失败')
      }
    },
    // 处理单个缩略图的选择
    handleThumbnailSelect(item) {
      if(this.isSingle){
        this.selectedIds = new Set()
      }
      if (item.selected) {
        this.selectedIds.add(item.imageId)
      } else {
        this.selectedIds.delete(item.imageId)
      }
      this.updateSelectAllStatus()
      this.updateSelectList()
    },
    // 处理全选/反选
    handleSelectAll() {
      const thumbnailList = this.thumbnailList;
      const selectedIds = this.selectedIds;
      const isAllSelected = this.isAllSelected;

      let index = 0;
      const updateBatchSize = 20; // 每次更新的数量

      const updateBatch = () => {
        for (let i = 0; i < updateBatchSize && index < thumbnailList.length; i++) {
          const item = thumbnailList[index++];
          item.selected = isAllSelected;
          if (isAllSelected) {
            selectedIds.add(item.imageId);
          } else {
            selectedIds.delete(item.imageId);
          }
        }

        if (index < thumbnailList.length) {
          requestAnimationFrame(updateBatch);
        } else {
          this.updateSelectList();
        }
      };

      requestAnimationFrame(updateBatch);
    },
    // 更新全选状态
    updateSelectAllStatus() {
      this.isAllSelected = this.thumbnailList.every(item => item.selected)
    },
    // 更新选择列表
    updateSelectList() {
      let allSelected = [];
      const uniqueIds = new Set();
      Object.values(this.allThumbnailData).forEach(batch => {
        batch.forEach(item => {
          if (this.selectedIds.has(item.imageId) &&!uniqueIds.has(item.imageId)) {
            allSelected.push(item);
            uniqueIds.add(item.imageId);
          }
        });
      });
      this.selectList = allSelected;
    },
    // 初始化选择数据
    initSelectData() {
      this.allThumbnailData = []
      this.selectList = []
      this.selectedIds.clear()
      this.init()
      this.thumbnailList.forEach(item => {
        item.selected = false
      })
    },
    // 处理卡片点击事件
    handleCardClick(item) {
      this.$set(item,'selected',!item.selected)
      this.handleThumbnailSelect(item)
    },
    // 获取选中的数据
    getSelectedData() {
      return this.selectList
    },
    init: debounce(async function() {
      if(this.activeName === 'all'){
        await this.getNotExistsRecords()
      } else {
        await this.getHistoryRecords()
      }
    },500),
    handleClick(){
      setTimeout(() => {
        this.init()
      },50)
    },
  },
  mounted() {
    this.init()
  }
}
</script>

<style scoped lang="scss">
::v-deep{
  .el-card__body{
    height: calc(100% - 40px );
  }
}

.fill-width-height {
  width: 100%;
  height: 100%;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-col {
  display: flex;
  flex-direction: column;
}

.flex-1 {
  flex: 1;
}

.align-center {
  align-items: center;
}

.justify-start {
  justify-content: flex-start;
}

.overflow-auto {
  overflow: auto;
}

.selected{
  background-color: #00afff!important;
  color: #fff!important;
}

.history-list-container {
  border-right: 1px solid #eaeaea;
  padding: 16px;
  display: flex;
  flex-direction: column;
  max-height: 100vh; /* 最大高度为视口高度 */
  height: 100%;
}

/* 新增的标题框样式 */
.history-list-title {
  padding-bottom: 16px;
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 16px;
}

.history-list-title h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.history-records-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.history-records {
  overflow-y: auto;
  height: 100%;
}

.history-record-item {
  padding: 12px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: #f5f5f5;
  }
}

.record-urls {
  height: 60px;
  overflow: auto;
  font-size: 12px;
  color: #666;
}

.pagination-container {
  padding-top: 16px;
  margin: 0;
  height: 35px;
}

::v-deep {
  .el-divider--horizontal{
    margin: 0!important;
  }
}

.thumbnail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  max-height: 100vh; /* 最大高度为视口高度 */
}

.thumbnail-card-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.thumbnail-card-container {
  height: 100%;
  overflow-y: auto;
}

.thumbnail-card {
  height: 200px; /* 固定卡片高度 */
  transition: box-shadow 0.2s ease;

  &:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }
}

.image-wrapper {
  height: calc(100% - 30px); /* 减去头部高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.thumbnail-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  //height: 70px;
  padding: 12px;
  border-top: 1px solid #eaeaea;
}

.no-thumbnail-message {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}
</style>
